package com.abcdefg.demo.rpc;

import com.abcdefg.demo.constants.Constants;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RpcServer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.建立连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(Constants.Host);
        factory.setPort(Constants.Port);
        factory.setVirtualHost(Constants.VirtualHost);
        factory.setUsername(Constants.UserName);
        factory.setPassword(Constants.Password);
        Connection connection = factory.newConnection();
        //2.创建信道
        Channel channel = connection.createChannel();
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE2, true, false, false, null);

        //3. 接收消息, 并消费
        // 设置同时最多只能获取⼀个消息
        channel.basicQos(1);
        DefaultConsumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收到消息: " + new String(body));
                String response = "接收到request:"+new String(body)+",处理并返回";
                AMQP.BasicProperties basicProperties=new AMQP.BasicProperties()
                        .builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                channel.basicPublish("",Constants.RPC_RESPONSE_QUEUE1,basicProperties,response.getBytes());

                //手动确认收到
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        channel.basicConsume(Constants.RPC_REQUEST_QUEUE2,false,consumer);
    }
}
